<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1,shrink-to-fit=no"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="./pwacompat.min.js" async></script>
    <link rel="manifest" href="./manifest.json" />
    <title>PWA 特性检测</title>
    <style>
      @media screen and (min-width: 500px) {
        body {
          width: 500px;
          margin: 0 auto;
        }
      }
      #push_body {
        overflow-x: auto;
      }
      fieldset {
        min-width: 0;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      legend {
        min-width: 0;
        max-width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    </style>
  </head>

  <body>
    <div>
      <img src="net.jpg" width="100%" />
    </div>

    <div id="sw_msg"></div>

    <fieldset>
      <legend>Notification 通知 API</legend>
      <div id="noti_status">状态：...</div>
      <button id="noti_reqest_btn">请求通知授权</button>
      <button id="noti_show">试一下效果</button>
    </fieldset>

    <fieldset>
      <legend>Push 消息推送 API</legend>
      <div id="push_status">状态：未订阅</div>
      <div id="push_body"></div>
      <button id="push_subscription">订阅</button>
      <button id="push_unsubscribe">退订</button>
    </fieldset>

    <fieldset>
      <legend>安装应用</legend>
      <button id="install_app_btn" disabled>安装应用</button>
    </fieldset>

    <fieldset>
      <legend>消息通讯</legend>
      <button id="msg_channel">单信道通讯</button>
      <button id="msg_broadcast">广播通讯</button>
      <button id="msg_clients">Clients广播通讯</button>
    </fieldset>

    <fieldset>
      <legend>后台同步</legend>
      <button id="sync_btn">Sync。</button>
    </fieldset>

    <button id="pay">支付</button>
    <div>
      <a href="./fullscreen/">fullscreen</a>
      <a href="./standalone/">standalone</a>
      <a href="./minimal-ui/">minimal-ui</a>
      <a href="./browser/">browser</a>
    </div>

    <script src="https://g.alicdn.com/platform/lp-cdn/0.1.10/lp-reg-sw.es5.js"></script>
    <script>
      var noti_status = document.getElementById("noti_status");
      var noti_reqest_btn = document.getElementById("noti_reqest_btn");
      var noti_show = document.getElementById("noti_show");
      var sw_msg = document.getElementById("sw_msg");
      var push_status = document.getElementById("push_status");
      var push_body = document.getElementById("push_body");
      var push_subscription = document.getElementById("push_subscription");
      var push_unsubscribe = document.getElementById("push_unsubscribe");
      var msg_channel = document.getElementById("msg_channel");
      var msg_broadcast = document.getElementById("msg_broadcast");
      var msg_clients = document.getElementById("msg_clients");
      var install_app_btn = document.getElementById("install_app_btn");
      var sync_btn = document.getElementById("sync_btn");
      var pushOption = {
        userVisibleOnly: true,
        applicationServerKey: urlB64ToUint8Array(
          "BDTgN25YAAabqE6ANPP49d2EkoLAMxT4xDZxE5BdrCHPyq1zk36LofZ2M3DYosxZzSG7i_26S1ViOGC_rBifW_U"
        )
      };

      var bc = new BroadcastChannel("detect");
      bc.onmessage = e => {
        console.log("广播通讯收到消息(Window环境)", e);
      };

      msg_clients.addEventListener("click", () => {
        navigator.serviceWorker.controller.postMessage({
          type: "clients-broadcast",
          data: "clients广播通讯"
        });
      });

      msg_channel.addEventListener("click", () => {
        if (!navigator.serviceWorker.controller) {
          alert("ServiceWorker 未受控，请刷新页面");
          return;
        }

        var c = new MessageChannel();

        c.port1.onmessage = e => {
          console.log("单信道通讯收到消息(Window环境)", e);
        };
        navigator.serviceWorker.controller.postMessage(
          {
            type: "channel",
            data: "单信道通讯"
          },
          [c.port2]
        );
      });

      msg_broadcast.addEventListener("click", () => {
        navigator.serviceWorker.controller.postMessage({
          type: "broadcast",
          data: "广播通讯"
        });
      });

      // notification
      if (window.Notification) {
        noti_status.innerText = "状态：" + Notification.permission;
        noti_show.addEventListener("click", function() {
          if (Notification.permission != "granted") {
            alert("请先授权通知");
            return;
          }
          new Notification("这是标题", {
            body: "Hellow，这是内容",
            icon:
              "https://img.alicdn.com/tfs/TB1trTQhu3tHKVjSZSgXXX4QFXa-2079-1349.png"
          });
        });
        Notification.permission &&
          noti_reqest_btn.addEventListener("click", function() {
            Notification.requestPermission().then(function() {
              noti_status.innerText = "状态：" + Notification.permission;
            });
          });
      } else {
        noti_status.innerText = "状态：浏览器不支持";
        noti_reqest_btn.disabled = true;
      }

      if ("serviceWorker" in navigator) {
        // ----
        (function() {
          _print("开始执行注册函数");
          navigator.serviceWorker.addEventListener("controllerchange", () => {
            navigator.serviceWorker.controller.addEventListener(
              "statechange",
              e => {
                installingWorker = e.target;
                _print(
                  "controller 触发 onstatechange ==> registration.installing",
                  "state => " + installingWorker.state,
                  installingWorker,
                  "e.target == installingWorker",
                  e.target == installingWorker,
                  e.target.state
                );
              }
            );
          });

          register({
            ver: 7,
            path: ".",
            name: "sw.pwa.js"
          });

          function emitUpdate(data) {
            var event = document.createEvent("Event");
            event.initEvent("sw.update", true, true);
            event.data = data;
            window.dispatchEvent(event);
          }

          function register(config) {
            if ("serviceWorker" in navigator) {
              navigator.serviceWorker.addEventListener(
                "controllerchange",
                e => {
                  _print("触发事件 controllerchange", e);
                }
              );

              var swUrl = config.path + "/" + config.name + "?v=" + config.ver;
              navigator.serviceWorker
                .register(swUrl)
                .then(function(registration) {
                  _print(
                    "执行 register 函数完成 ==> registration",
                    registration
                  );
                  if (config && config.onRegster) {
                    config.onRegster(registration);
                  }

                  registration.onupdatefound = function(e) {
                    _print(
                      "触发 onupdatefound 事件 ==> registration",
                      registration,
                      e.target
                    );
                    // var installingWorker = registration.installing;
                    var installingWorker =
                      e.target.installing ||
                      e.target.waiting ||
                      e.target.active;
                    if (installingWorker == null) {
                      return;
                    }
                    installingWorker.addEventListener("statechange", e => {
                      _print(
                        "触发 onstatechange ==> registration.installing",
                        "state => " + installingWorker.state,
                        installingWorker,
                        "e.target == installingWorker",
                        e.target == installingWorker,
                        e.target.state
                      );
                      if (installingWorker.state === "installed") {
                        if (navigator.serviceWorker.controller) {
                          _print("controller 已受控，所以属于更新行为");

                          if (config && config.onUpdate) {
                            config.onUpdate(registration);
                          }
                        } else {
                          _print("controller 未受控，所以属于第一次操作。");

                          if (config && config.onSuccess) {
                            config.onSuccess(registration);
                          }
                        }
                      }
                    });
                  };
                })
                .catch(function(error) {
                  console.error("serviceWorker注册期间发生错误:", error);
                });
            }
          }

          function unregister() {
            if ("serviceWorker" in navigator) {
              navigator.serviceWorker.ready.then(function(registration) {
                registration.unregister();
              });
            }
          }

          function _print(...args) {
            var _console;

            (_console = console).log.apply(
              _console,
              [
                "%c lp-pwa ",
                "background: #0f0; color: #555; padding: 2px 0.5em; " +
                  "border-radius: 0.5em;"
              ].concat([args])
            );
          }
        })();

        // ====

        navigator.serviceWorker.onmessage = e => {
          console.log("clients广播通讯收到消息(Window环境)", e);
        };
      } else {
        sw_msg.innerHTML =
          '当前浏览器<font color="red">不支持</font> ServiceWorker';
      }

      if (!window.PushManager) {
        push_status.innerHTML = "状态：浏览器不支持";
      } else if ("serviceWorker" in navigator) {
        push_unsubscribe.addEventListener("click", function() {
          navigator.serviceWorker.ready.then(function(swReg) {
            swReg.pushManager
              .getSubscription()
              .then(function(pushSubscription) {
                pushSubscription.unsubscribe().then(function(result) {
                  if (result) {
                    push_status.innerHTML = "状态：已退订";
                    push_body.innerHTML = "";
                  }
                });
              });
          });
        });
        push_subscription.addEventListener("click", function() {
          navigator.serviceWorker.ready.then(function(swReg) {
            swReg.pushManager
              .subscribe(pushOption)
              .then(function(pushSubscription) {
                push_body.innerHTML =
                  "订阅体：<pre>" +
                  JSON.stringify(pushSubscription, null, 2) +
                  "</pre>";
                push_status.innerText = "状态：已订阅";
              });
          });
        });
        navigator.serviceWorker.ready.then(function(swReg) {
          swReg.pushManager.getSubscription().then(function(pushSubscription) {
            if (pushSubscription) {
              push_status.innerText = "状态：已订阅";
              push_body.innerHTML =
                "订阅体：<pre>" +
                JSON.stringify(pushSubscription, null, 2) +
                "</pre>";
            }
          });
        });
      }

      sync_btn.addEventListener("click", () => {
        navigator.serviceWorker.ready.then(reg => {
          reg.sync
            .register("同步")
            .then(() => reg.sync.getTags())
            .then(tags => {
              console.log("已注册 Sync Tags", tags);
            });
        });
      });

      window.addEventListener("beforeinstallprompt", function(e) {
        e.preventDefault();
        window.ePrompt = e;
        install_app_btn.disabled = false;
        install_app_btn.addEventListener("click", () => {
          window.ePrompt.prompt();
        });
      });

      window.addEventListener("appinstalled", evt => {
        console.log("appinstalled 已安装到桌面屏幕", evt);
      });

      function urlB64ToUint8Array(base64String) {
        const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
        const base64 = (base64String + padding)
          .replace(/\-/g, "+")
          .replace(/_/g, "/");

        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);

        for (let i = 0; i < rawData.length; ++i) {
          outputArray[i] = rawData.charCodeAt(i);
        }
        return outputArray;
      }

      pay.onclick = () => {
        function initPaymentRequest() {
          let networks = ["amex", "jcb", "visa"];

          let supportedInstruments = [
            {
              supportedMethods: "basic-card",
              data: {
                supportedNetworks: networks,
                supportedTypes: ["debit", "credit", "prepaid"]
              }
            },
            {
              supportedMethods: "https://apple.com/apple-pay",
              data: {
                version: 2,
                supportedNetworks: networks,
                countryCode: "CN",
                merchantIdentifier: "detect.pwa",
                merchantCapabilities: [
                  "supportsDebit",
                  "supportsCredit",
                  "supports3DS"
                ]
              }
            }
          ];

          let details = {
            total: {
              label: "支付",
              amount: { currency: "EUR", value: "10.00" }
            },
            displayItems: [
              {
                label: "Original donation amount",
                amount: { currency: "EUR", value: "10.00" }
              }
            ]
          };

          return new PaymentRequest(supportedInstruments, details);
        }
        initPaymentRequest().show();
      };

      // puk key
      // BDTgN25YAAabqE6ANPP49d2EkoLAMxT4xDZxE5BdrCHPyq1zk36LofZ2M3DYosxZzSG7i_26S1ViOGC_rBifW_U
      // pri key
      // MlbSc85-wr7Dh9k2XvE5_yquFFZ_D8mlr2_SlGwmCmc
      /*
        {
          "title": "采购商城14442",
          "body": "采购单已生成，请点击下载~",
          "icon": "https://img.alicdn.com/tfs/TB1trTQhu3tHKVjSZSgXXX4QFXa-2079-1349.png",
          "data": {
            "nav": "https://lecepin.gitee.io/detect-sw"
          }
        }
        */
    </script>
  </body>
</html>
